package com.devshephard.business;

import com.devshephard.entity.Greeting;
import com.devshephard.entity.HelloMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.converter.SimpleMessageConverter;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;

import javax.websocket.Session;
import java.io.IOException;

@Controller
public class WebSocketController {

    @Autowired
    SimpMessagingTemplate simpMessagingTemplate;

    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting greeting(HelloMessage message) throws IOException {
        return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
    }

    @GetMapping("/sendToIndex")
    @ResponseBody
    public void sendToIndex() throws IOException {
        HelloMessage message = new HelloMessage();
        message.setName("服务器消息推送");
        simpMessagingTemplate.convertAndSend("/topic/greetings",new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!"));
    }

    @GetMapping("/webSocketPage")
    public String webSocketPage() {
        return "index/sockIndex";
    }

}
